import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:sjx/common_ui/loading.dart';
import 'package:sjx/repository/model/task_detail_model.dart';
import 'package:sjx/repository/model/user_model.dart';
import 'package:sjx/repository/sjx_api.dart';
import 'package:sjx/route/route_utils.dart';
import 'package:sjx/route/routes.dart';
import 'package:sjx/utils/sp_utils.dart';

class TaskDetailViewModel with ChangeNotifier {
  TaskDetailModel? _taskDetailModel;
  bool _isLoading = false;
  String? _error;
  String? _taskNo;

  TaskDetailModel? get taskDetailModel => _taskDetailModel;

  bool get isLoading => _isLoading;

  String? get error => _error;

  // 添加空对象的工厂方法
  static TaskDetailModel get empty => TaskDetailModel(
    approveCount: 0,
    approveUserAvatars: [],
    bidSubmitDurationTimeDisplay: '',
    bidTimesByUser: 0,
    blackUser: false,
    deviceType: '',
    endTimeDisplay: '',
    leftBidTime: 0,
    openView: '',
    orderNo: '',
    publisherName: '',
    publisherPlatformId: '',
    publisherVartar: '',
    pushUserid: null,
    readSeconds: 0,
    rewardAmountDisplay: '',
    statusLabel: '',
    taskCategory: '',
    taskDescription: '',
    taskLinks: [],
    taskNo: '',
    taskRequirement: '',
    taskRequirementImages: [],
    taskStatus: '',
    taskStepImages: [],
    taskStepList: [],
    taskSteps: '',
    taskTitle: '加载中...',
    taskType: '',
  );

  //请求详情
  Future<void> requestTaskDetail(String taskNo) async {
    _taskNo = taskNo;
    _taskDetailModel = await SJXApi.instance().taskDetail(taskNo);
    notifyListeners();
  }

  Future<void> actionTask(BuildContext context) async {
    //判断用户是否登录
    final userModel = await SpUtils.getUserData();
    if (userModel != null) {
      if (_taskDetailModel?.taskStatus == "待领取") {
        Loading.showLoading();
        await SJXApi.instance().receiveTask(_taskDetailModel!.taskNo);
        await requestTaskDetail(_taskDetailModel!.taskNo);
        Loading.dismissAll();
        notifyListeners();
      } else if (_taskDetailModel?.taskStatus == "待提交" ||
          _taskDetailModel?.taskStatus == "已拒绝") {
        RouteUtils.pushForNamed(
          context,
          RoutePath.task_submit,
          arguments: {'taskNo': _taskDetailModel?.taskNo},
        ).then((_) {
          requestTaskDetail(_taskNo!);
        });
      }
    } else {
      final result = await showOkCancelAlertDialog(
        context: context,
        title: "提示",
        message: "请登录后体验更多功能",
        okLabel: "去登录",
        cancelLabel: "取消",
      );
      if (result == OkCancelResult.ok) {
        RouteUtils.pushForNamed(context, RoutePath.login);
      }
    }
  }
}
